package com.ittx.dzt.weidian.handler;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 微店平台API处理父类
 * <p>
 *
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/3/25
 */
@Slf4j
public abstract class AbstractBaseWeidianApiHandler<T> extends AbstractBasePlatformApiHandler<T> {

	@Autowired
	protected RocketmqProducer rocketmqProducer;

	/**
	 * 查询总数
	 */
	public static final String RESULT_TOTAL = "total_num";

	@Override
	public String getPlatformCode() {
		return PlatformConstant.WEIDIAN;
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 */
	public Result executeWeidianApi(StoreConfigDTO storeConfig, Map<String, Object> paramMap, String requestId) {
		// 序列化参数
		String paramJson = JacksonTool.toJson(paramMap);
		// 发起请求
		Result<?> result = null;
		try {
			result = fetch(storeConfig, paramJson, requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = (Map<String, Object>) result.getData();
				Map<String, Object> statusMap = (Map<String, Object>) resultMap.get("status");
				if (!"0".equals(MapUtil.getStr(statusMap, "status_code"))) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getWeidianMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(resultMap.get("msg") + "-" + resultMap.get("sub_msg"));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getWeidianMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getWeidianMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param storeConfig 店铺配置
	 * @param paramJson   请求参数
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result<?> fetch(StoreConfigDTO storeConfig, String paramJson, String requestId) throws Exception {
		Map<String, String> publicReqMap = Maps.newHashMap();
		publicReqMap.put("method", this.getWeidianMethod());
		publicReqMap.put("version", this.getWeidianApiVersion());
		publicReqMap.put("access_token", storeConfig.getSessionKey());
		if (StrUtil.isNotEmpty(this.getWeidianApiFormat())) {
			publicReqMap.put("format", this.getWeidianApiFormat());
		}
		HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);
		if (httpRequestTemplate == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
		}
		Map<String, String> reqMap = Maps.newHashMap();
		reqMap.put("param", paramJson);
		reqMap.put("public", JacksonTool.toJson(publicReqMap));
		log.debug("url:{},param:{},public:{}", storeConfig.getSdkUrl(), paramJson, reqMap.get("public"));
		String returnMsg = httpRequestTemplate.postFormParams(storeConfig.getSdkUrl(), reqMap);
		log.debug("respBody:{}", returnMsg);
		if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isTypeJSON(returnMsg)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
					, this.getWeidianMethod(), storeConfig.getSdkUrl(), returnMsg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
		}
		Map resultMap = JacksonTool.toEntity(returnMsg, Map.class);
		return Result.success().addData(resultMap);
	}

	/**
	 * 获取微店平台方法名称
	 *
	 * @return
	 */
	public abstract String getWeidianMethod();

	/**
	 * 获取微店平台方法版本
	 *
	 * @return
	 */
	public String getWeidianApiVersion() {
		return "1.5";
	}

	/**
	 * 获取微店平台api格式
	 *
	 * @return
	 */
	public abstract String getWeidianApiFormat();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	/**
	 * 时间格式转换
	 */
	public String timeToString(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC);
		return df.format(localDateTime);
	}

	public String format(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
		return df.format(localDateTime);
	}
}
